//
//  COVideoContent.swift
//  CocoProject
//
//  Created by Vill on 2023/11/10.
//

import UIKit
import SwiftyJSON

class COVideoContent: RCMessageContent {

    var streamerID: Int64?       // 对方ID
    var streamerName: String?    // 对方昵称
    var customerID: Int64?       // 自己id
    var customerName: String?    // 自己昵称
    var cost: Int?               // 金币数

    ///消息是否存储，是否计入未读数
    override class func persistentFlag() -> RCMessagePersistent {
        return RCMessagePersistent.MessagePersistent_ISPERSISTED
    }
    
    //最后一条消息是自定义消息的时候，可以更改在会话列表显示的类型，为了区分消息类型
    override func conversationDigest() -> String? {
        return "[Video Talk]"
    }
    
    //定义的消息类型名，需要在各个平台上保持一致，以保证消息互通,别以 RC 开头，以免和融云系统冲突
    override class func getObjectName() -> String {
        return "RC:VideoTalkMsg"
    }
    
    override func encode() -> Data? {
        var dataDict = [String: Any]()
        if let senderUserInfo = self.senderUserInfo {
            var userInfoDict = [String: String]()
            userInfoDict["userId"] = senderUserInfo.userId
            userInfoDict["name"] = senderUserInfo.name
            userInfoDict["portraitUri"] = senderUserInfo.portraitUri
            dataDict["user"] = userInfoDict
        }
        dataDict["streamerID"] = streamerID
        dataDict["streamerName"] = streamerName
        dataDict["customerID"] = customerID
        dataDict["customerName"] = customerName
        dataDict["cost"] = cost
        if let data = try? JSONSerialization.data(withJSONObject: dataDict, options: []) {
            return data
        }
        return nil
    }
    
    override func decode(with data: Data) {
        if let dict = try? JSONSerialization.jsonObject(with: data, options: []) {
            let json = JSON(dict)
            streamerID = json["streamerID"].int64
            streamerName = json["streamerName"].string
            customerID = json["customerID"].int64
            customerName = json["customerName"].string
            cost = json["cost"].int
            
            if let user = json["user"].dictionary {
                let userInfo = RCUserInfo()
                userInfo.name = user["name"]?.string ?? ""
                if let portraitUri = user["portraitUri"]?.string {
                    userInfo.portraitUri = portraitUri
                }else {
                    userInfo.portraitUri = user["portrait"]?.string
                }
                if let userId = user["userId"]?.string {
                    userInfo.userId = userId
                }else {
                    userInfo.userId = user["id"]?.string ?? ""
                }
                self.senderUserInfo = userInfo
            }
        }
    }
    
}
